package top.minishow.pdf.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import top.minishow.pdf.entity.PdfPageHeadOutDTO;
import top.minishow.pdf.entity.PdfPageItemOutDTO;
import top.minishow.pdf.entity.PdfPageOutDTO;
import top.minishow.pdf.utils.FileUtil;
import top.minishow.pdf.utils.HtmlToPdf;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@RequestMapping
@RestController
public class TestController {
    @Autowired
    private Context context;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${html.file.path}")
    private String htmlDicPath;
    @Value("${wkhtmltopdf.path}")
    private String wkhtmltopdfPath;

//    @GetMapping("/down/{orderNumber}")
//    public String down(HttpServletResponse response, @PathVariable("orderNumber") String orderNumber) {
//        try {
//            String fileName = new String((orderNumber + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATE_PATTERN) + ".pdf").getBytes(), StandardCharsets.ISO_8859_1);
//            response.reset(); // 必要地清除response中的缓存信息
//            response.setContentType("application/vnd.ms-excel;charset=utf-8");
//            response.setHeader("name", fileName);
//            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
//            response.setHeader("Pragma", "public");
//            response.setDateHeader("Expires", 0);
//            response.setHeader("Access-Control-Allow-Origin", "*");
//            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
//            response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"" + ".pdf");
//            String filepath = success(0);
//            if (ObjectUtil.isNull(filepath)) {
//                return "error";
//            }
//            File file = new File(filepath);
//            try (
//                    InputStream inStream = new FileInputStream(file);
//                    ServletOutputStream outStream = response.getOutputStream()
//            ) {
//                byte[] buf = new byte[4096];
//                int readLength;
//                while (((readLength = inStream.read(buf)) != -1)) {
//                    outStream.write(buf, 0, readLength);
//                }
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return "ok";
//    }


    @GetMapping("/{number}")
    public String success(@PathVariable("number") int number) {
        final long l = System.currentTimeMillis();
        /**
         * 根据行来判断分页
         */
        for (int i = 0; i < number; i++) {
            extracted(i);
        }
        String extracted = extracted(0);
        final long l1 = System.currentTimeMillis();
        System.out.println("耗费时间");
        System.out.println((l1 - l) / 1000);
        if (ObjectUtil.isNull(extracted)) {
            return "error";
        }
        return extracted;
    }

    private String extracted(Integer i) {
        List<PdfPageOutDTO> list = getPage();
        String jsonString = JSON.toJSONString(list, SerializerFeature.WriteNullStringAsEmpty);
        List<PdfPageOutDTO> pdfPageOutDTOS = JSON.parseArray(jsonString, PdfPageOutDTO.class);
        context.setVariable("pageList", pdfPageOutDTOS);
        String format = i + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN);
        String htmlPath = htmlDicPath + format + ".html";
        String pdfPath = htmlDicPath + format + ".pdf";
        String htmlTemplate = "quectel";
        String htmlBody = templateEngine.process(htmlTemplate, context);
        FileUtil.write(htmlPath, htmlBody);
        boolean convert = HtmlToPdf.convert(wkhtmltopdfPath, htmlPath, pdfPath);
        return convert ? pdfPath : null;
    }

    public List<PdfPageOutDTO> getPage() {
        List<PdfPageItemOutDTO> itemList = getItem(10);
        int pageSize = 18;
        int totalPage = itemList.size() / pageSize + ((itemList.size() % pageSize) == 0 ? 0 : 1);
        int tempIndex = 0;
        List<PdfPageOutDTO> result = new ArrayList<>();
        for (int i = 0; i < totalPage; i++) {
            PdfPageOutDTO pdfPage = new PdfPageOutDTO();
            pdfPage.setHead(getHead());
            List<PdfPageItemOutDTO> tempList = new ArrayList<>();
            for (int j = 0; j < pageSize && tempIndex < itemList.size(); j++) {
                PdfPageItemOutDTO item = itemList.get(tempIndex);
                tempList.add(item);
                tempIndex++;
            }
            pdfPage.setList(tempList);
            result.add(pdfPage);
        }
        return result;
    }

    private PdfPageHeadOutDTO getHead() {
        PdfPageHeadOutDTO head = new PdfPageHeadOutDTO(null, "2", "3", "4", "5", "6", "4100014789", "安徽美年大健康管理咨询有限公司合肥包河美年大健康门诊部", "9", "10", "11", "12", null, null, "15", "16", "17", "18", "19", "20", "21", "22", "23", "5.111", null, "rebate po");
        return head;
    }

    private List<PdfPageItemOutDTO> getItem(int num) {
        List<PdfPageItemOutDTO> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            PdfPageItemOutDTO item = new PdfPageItemOutDTO(String.valueOf(i + 1), "s2", "d3", "f4", "g5", "h6", "j7", "k8", "l9");
            list.add(item);
        }
        return list;
    }
}
